用dictionary实现Python没有的switch语句 您所在的位置:网站首页 python switch语法 用dictionary实现Python没有的switch语句

用dictionary实现Python没有的switch语句

#用dictionary实现Python没有的switch语句 | 来源: 网络整理| 查看: 265

switch 语句,想必大家都很清楚了。以PHP为例,switch 语句大概是这样的:

switch ($value) { case 'a': $result = "nowamagic.net"; break; case 'b': $result = "google.com"; break; case 'c': $result = "z.cn"; break; }

但 Python 本身没有 switch 语句,那么 Python 如何实现 switch 这样的功能呢?

可以用 Python 内置的 dictionary (字典)数据类型来模拟,比如:

def test_switch(request, offset): dictionarys = { 'a':'nowamagic.net', 'b':'google.com', 'c':'z.cn', 'default':'none' } html = dictionarys.get(offset) return HttpResponse(html)

访问 http://127.0.0.1:8000/switchs/a/,页面显示:nowamagic.net

当然还有其它方法,我们从这里开始理解 Python 里的 dictionary 数据类型。



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有